function URLEncode(clearString){
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length){
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != ''){
            output += match[1];
            x += match[1].length;
        } else{
            if (clearString[x] == ' ')
            output += '+';
            else{
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0': '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

var nmt = {
    cmdUrl: null,

    playUrl: null,

    setAddr: function(addr)
    {
        var pos = location.href.indexOf('?addr=');
        if (pos != -1)
        {
            addr = location.href.substring(pos + 6);
        }

        this.cmdUrl = 'http://' + addr + ':9999/PLoNK_web/plonk_nmt.php?func=';
        //this.playUrl = 'http://' + addr + ':9999/ytlr/play.php?play=';
        this.playUrl = 'http://' + addr + ':9999/inmt/play.php?play=';
    },

    doneUrl: null,

    setDoneURL: function(url)
    {
        this.doneUrl = url;
    },

    get: function(url)
    {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function()
        {
            };
        req.open("GET", url, true);
        req.send(null);
    },

    command: function(cmd)
    {
        if (this.cmdUrl == null)
        {
            alert("nmt.setAddr(ip.address.of.nmt) hasn't been called.");
        }
        else
        {
            this.get(this.cmdUrl + cmd);
        }
    },

    play: function(file)
    {
        if (this.playUrl == null)
        {
            alert("nmt.setAddr(ip.address.of.nmt) hasn't been called.");
        }
        else
        {
            var pos = file.indexOf('://');
            if (pos == -1)
            {
                var url = window.location.href;
                pos = url.lastIndexOf('/')
                if (pos != -1)
                {
                    file = url.substr(0, pos + 1) + file;
                }
            }
            file = URLEncode(file);
            var cmd = this.playUrl + file;
            if (this.doneUrl != null)
            {
                cmd = cmd + '&done=' + this.doneUrl;
            }
            this.get(cmd);
        }
    }
}

